package chapter_23.security;

/**
 * 多线程同步方法的测试(访问"临界资源")
 * (Synchronized 关键字)
 */
public class TicketTest {

    public static void main(String[] args) {

        TicketDB ticketDB = new TicketDB();

        // 创建线程 t1
        Thread t1 = new Thread(() -> {
            function(ticketDB);
        });
        // 开始线程 t1
        t1.start();

        // 创建线程 t2
        Thread t2 = new Thread(() -> {
            function(ticketDB);
        });
        // 开始线程 t1
        t2.start();
    }

    public static void function(TicketDB ticketDB) {
        while (true) {
            int currTicketCount = ticketDB.getTicketCount();
            // 查询是否有票
            if (currTicketCount > 0) {
                ticketDB.sellTicket();
            } else {
                // 无票退出
                break;
            }
        }
    }

}
